/** 
 * File-Name:ArticleAction.java
 *
 * Created on 2011-6-2 下午10:10:52
 * 
 * @author: Neo (neolimeng@gmail.com)
 * Software Engineering Institute, Peking University, China
 * 
 * Copyright (c) 2009, Peking University
 * 
 *
 */
package site.web;

import java.io.File;
import java.io.InputStream;
import java.net.URLEncoder;
import java.util.LinkedList;
import java.util.List;

import javax.servlet.Servlet;

import org.apache.log4j.Logger;

import neoutil.CommonAction;
import neoutil.CommonService;
import neoutil.Config;
import neoutil.FileUtils;
import neoutil.Page;
import site.entity.Category;
import site.entity.Resource;
import site.entity.Role;
import site.entity.User;
import site.helper.Catalog;
import site.helper.CommonHelper;
import site.helper.CourseTitle;
import site.service.CategoryRepository;
import site.service.ResourceRepository;

/**
 * Description:
 * 
 * @author: Neo (neolimeng@gmail.com) Software Engineering Institute, Peking
 *          University, China
 * @version 1.0 2011-6-2 下午10:10:52
 */
public class ResourceAction extends CommonAction {
	private static Logger log = Logger.getLogger(ResourceAction.class);
	private static final long serialVersionUID = -6070258801885753740L;
	private int cid;
	private Category category;
	private List<Category> categories;

	private File resourceFile;
	private String resourceFileContentType;
	private String resourceFileFileName;

	private Resource r;
	private Page<Resource> page = new neoutil.Page<Resource>(15);

	private String chapter;
	private String chapters;
	private String query;

	public String toAddResource() {
		try {
			cid = Integer.parseInt(getRequestParameter("cid"));
			category = getCategoryRepository().getCategoryByCid(cid);
			return SUCCESS;
		} catch (Exception e) {
			e.printStackTrace();
			return ERROR;
		}
	}

	public String addResource() {
		if (resourceFile != null) {
			log.info("资源附件名称为：" + getResourceFileFileName());
			String fileName = r.getUuid() + FileUtils.getExtention(getResourceFileFileName());
			FileUtils.copy(getResourceFile(), new File(Config.getResourceSavePath() + fileName));

			r.setFileName(fileName);
		} else {
			log.warn("资源无附件！");
		}

		User user = (User) getSessionObject("loginUser");
		if (null == user) {
			return ERROR;
		} else {

			if (r.getCourse().equals(CourseTitle.GYK)) {
				r.setCid(13);
			} else if (r.getCourse().equals(CourseTitle.GLK)) {
				r.setCid(12);
			} else if (r.getCourse().equals(CourseTitle.JCK)) {
				r.setCid(14);
			} else if (r.getCourse().equals(CourseTitle.SHYZC)) {
				r.setCid(28);
			} else if (r.getCourse().equals(CourseTitle.YLK)) {
				r.setCid(11);
			}

			cid = r.getCid();
			if (CommonHelper.IsNullOrEmpty(r.getTeamCode())) {
				r.setTeamCode(Config.getTeamCode());
			}

			r.setAuthor(user.getEmail());
			if (r.getAuthorRealName() == null || "".equals(r.getAuthorRealName())) {
				r.setAuthorRealName(user.getRealName());
				r.setProvider(user.getRealName());
			}

			getResourceRepository().save(r);
			if (user.getRid() == Role.GUSET) {
				return "redirect_guest";
			}

			return SUCCESS;
		}
	}

	public String manageResourcesByCid() {
		try {
			cid = Integer.parseInt(getRequestParameter("cid"));
			category = getCategoryRepository().getCategoryByCid(cid);

			User loginUser = (User) getSessionObject("loginUser");
			if (loginUser.getRid() <= 2) {
				page = getResourceRepository().getResourcesByCid(page, cid, -1);
			} else {
				page = getResourceRepository().getResourcesByCidAndAuthor(page, cid, loginUser.getEmail());
			}
			return SUCCESS;
		} catch (Exception e) {
			e.printStackTrace();
			return ERROR;
		}
	}

	public String viewResourcesByCid() {
		try {
			cid = Integer.parseInt(getRequestParameter("cid"));
			CategoryRepository categoryRepository = getCategoryRepository();

			if (cid == 100) {
				category = new Category();
				category.setName("搜索结果");
				categories = new LinkedList<Category>();
				categories.add(category);
				page = getResourceRepository().search(page, query);
				return SUCCESS;
			}

			category = categoryRepository.getCategoryByCid(cid);
			categories = categoryRepository.getCategoriesByParentCid(category.getParentCid());

			page = getResourceRepository().getResourcesByCid(page, cid, 2);
			return SUCCESS;
		} catch (Exception e) {
			e.printStackTrace();
			return ERROR;
		}
	}

	public String viewResourceByUuid() {
		try {
			String uuid = getRequestParameter("uuid");

			r = getResourceRepository().getResourceByUuid(uuid);
			int visitNum = r.getVisitNum() + 1;
			r.setVisitNum(visitNum);
			getResourceRepository().updateResource(r);
			CategoryRepository categoryRepository = getCategoryRepository();
			category = categoryRepository.getCategoryByCid(r.getCid());
			categories = categoryRepository.getCategoriesByParentCid(category.getParentCid());

			if(!CommonHelper.IsNullOrEmpty(r.getChapter()))
			{
				chapter = Catalog.valueOf(r.getChapter()).getText() + "，" + Catalog.valueOf(r.getChapter()).getTitle();
			}

			return SUCCESS;
		} catch (Exception e) {
			e.printStackTrace();
			return ERROR;
		}
	}

	public String downloadResource() {
		String uuid = getRequestParameter("uuid");
		r = getResourceRepository().getResourceByUuid(uuid);

		if (r != null && r.getFileName() != null && new File(Config.getResourceSavePath() + r.getFileName()).exists()) {
			return SUCCESS;
		} else {
			return ERROR;
		}
	}

	public InputStream getEnclosureFile() {
		try {
			String uuid = getRequestParameter("uuid");
			r = getResourceRepository().getResourceByUuid(uuid);
			r.setTitle(URLEncoder.encode(r.getTitle(), "UTF-8") + "." + CommonHelper.getExtension(r.getFileName()));
			return new java.io.FileInputStream(Config.getResourceSavePath() + "\\" + r.getFileName());
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}

	public String deleteResource() {
		try {
			String uuid = getRequestParameter("uuid");
			if (CommonService.SUCCESS.equals(getResourceRepository().deleteResourceByUuid(uuid))) {
				return SUCCESS;
			} else {
				return ERROR;
			}
		} catch (Exception e) {
			e.printStackTrace();
			return ERROR;
		}
	}

	public String toEditResource() {
		try {
			User user = (User) getSessionObject("loginUser");
			if (user == null) {
				return RELOGIN;
			} else {
				String uuid = getRequestParameter("uuid");
				if (uuid == null || "".equals(uuid)) {
					return ERROR;
				} else {
					r = getResourceRepository().getResourceByUuid(uuid);

					if (!CommonHelper.IsNullOrEmpty(r.getChapter())) {
						chapter = Catalog.valueOf(r.getChapter()).getText() + "，" + Catalog.valueOf(r.getChapter()).getTitle();
					}

					CategoryRepository categoryRepository = getCategoryRepository();
					category = categoryRepository.getCategoryByCid(r.getCid());
					return SUCCESS;
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
			return ERROR;
		}
	}

	public String editResource() {
		log.info(r.getTitle());

		// r = getResourceRepository().getResourceByUuid(r.getUuid());
		if (resourceFile != null) {
			log.info("资源附件名称为：" + getResourceFileFileName());
			String fileName = r.getUuid() + FileUtils.getExtention(getResourceFileFileName());
			FileUtils.copy(getResourceFile(), new File(Config.getResourceSavePath() + fileName));

			r.setFileName(fileName);
		} else {
			log.warn("资源无附件！");
		}

		if (chapter != null && (CommonHelper.IsNullOrEmpty(r.getChapters()) || !chapter.equals(r.getChapter()))) {
			r.setChapter(chapter);
		}
		if (chapters != null && (CommonHelper.IsNullOrEmpty(r.getChapters()) || !chapters.equals(r.getChapters()))) {
			r.setChapters(chapters);
		}
		if (CommonHelper.IsNullOrEmpty(r.getTeamCode())) {
			r.setTeamCode(Config.getTeamCode());
		}

		getResourceRepository().updateResource(r);

		return SUCCESS;
	}

	// Getters and Setters
	public int getCid() {
		return cid;
	}

	public void setCid(int cid) {
		this.cid = cid;
	}

	public Category getCategory() {
		return category;
	}

	public void setCategory(Category category) {
		this.category = category;
	}

	public List<Category> getCategories() {
		return categories;
	}

	public void setCategories(List<Category> categories) {
		this.categories = categories;
	}

	public Resource getR() {
		return r;
	}

	public void setR(Resource r) {
		this.r = r;
	}

	public Page<Resource> getPage() {
		return page;
	}

	public void setPage(Page<Resource> page) {
		this.page = page;
	}

	public File getResourceFile() {
		return resourceFile;
	}

	public void setResourceFile(File resourceFile) {
		this.resourceFile = resourceFile;
	}

	public String getResourceFileContentType() {
		return resourceFileContentType;
	}

	public void setResourceFileContentType(String resourceFileContentType) {
		this.resourceFileContentType = resourceFileContentType;
	}

	public String getResourceFileFileName() {
		return resourceFileFileName;
	}

	public void setResourceFileFileName(String resourceFileFileName) {
		this.resourceFileFileName = resourceFileFileName;
	}

	public void setChapters(String chapters) {
		this.chapters = chapters;
	}

	public String getChapters() {
		return chapters;
	}

	public void setChapter(String chapter) {
		this.chapter = chapter;
	}

	public String getChapter() {
		return chapter;
	}

	public String getQuery() {
		return query;
	}

	public void setQuery(String query) {
		this.query = query;
	}
}
